import { Breadcrumb, Button, Table, Space, Popconfirm, Modal, message, TableProps, DatePicker, Flex } from 'antd';
import React, { FC } from 'react';
import { LeftOutlined } from '@ant-design/icons';
import {
  FormPanel,
  Utils,
  type FormPanelObject,
  FormPanelBtnAlign,
  FormPanelBtnDisplay,
  InputType,
  RuleType,
  StandUploadExcel,
  FormPanelStatus,
} from 'lfun-bg-comp';
import dayjs from 'dayjs';
import { useParams, useNavigate } from 'react-router-dom';
import { PageContainer } from '@/component/page-container';
import { ATTACHED_TYPE, CLASSES_SYSTEM } from '@/constant/schoolOptions';
import { YES_NO } from '@/constant/basicOptions';
import utils, { get_stoge_pz, selectDictLabel, set_stoge_pz } from '@/utils';
import {
  CreateClasses,
  SearchClass,
  UpdateClasses,
  createClasses,
  importClass,
  searchClasses,
  updateClasses,
  deleteClasses,
} from '@/service/unit/classes';
import { PAGINATIONCONFIG } from '@/constant/page';
import { getSessionOptions, getGradeOptions, searchTeacherOptions, searchStudentOptions } from '@/service/options';
import { ID_TYPE } from '@/constant/studentOptions';
import { IMPORT_EXCEL_TEMPLATE } from '@/constant';
import PermissionButton, { isPermissionOperate } from '@/component/permission-button';

const { RangePicker } = DatePicker;

const Groups: FC = () => {
  const navigator = useNavigate();
  const [value, setValue] = React.useState([]);
  const [showModel, setShowModel] = React.useState(false);
  const [showEditModel, setShowEditModel] = React.useState(false);
  const [current, setCurrent] = React.useState<any>({});
  const [searchForm, setSearchForm] = React.useState(null);
  const [total, setTotal] = React.useState(0);
  const [pageSize, setPageSize] = React.useState(get_stoge_pz());
  const [pageIndex, setPageIndex] = React.useState(1);
  const [sessionOptions, setSessionOptions] = React.useState([]);
  const [gradeOptions, setGradeOptions] = React.useState([]);
  const isSchool = Utils.getProps('isSchool');
  const [isEdit, setIsEdit] = React.useState(true);
  const { school_id } = useParams();

  const columns: TableProps['columns'] = [
    {
      title: '编号',
      width: 100,
      dataIndex: 'index',
      key: 'index',
      align: 'center',
      fixed: 'left',
      render(val, row, index) {
        return index + 1;
      },
    },
    {
      title: '班级届别',
      dataIndex: 'session_id',
      key: 'session_id',
      width: 80,
      render(val) {
        return selectDictLabel(sessionOptions, val);
      },
    },
    // {
    //   title: '区域',
    //   dataIndex: 'block',
    //   key: 'block',
    //   width: 80,
    //   render: (text: any) => {
    //     return _.find(SY_ZONES, { value: String(text) })?.label;
    //   },
    // },
    // {
    //   title: '学校',
    //   dataIndex: 'school_name',
    //   key: 'school_name',
    //   width: 150,
    // },
    {
      title: '班级名称',
      dataIndex: 'class_name',
      key: 'class_name',
      width: 80,
    },

    (() => {
      const k12 = {
        title: '所属年级',
        dataIndex: 'grade_id',
        key: 'grade_id',
        width: 80,
        render(val) {
          return selectDictLabel(gradeOptions, val);
        },
      };
      const notK12 = {
        title: '所属班级类型',
        dataIndex: 'class_type_name',
        key: 'class_type_name',
        width: 120,
      };
      return Utils.getProps('edu_type') === 'k12' ? k12 : notK12;
    })(),
    // {
    //   title: '班号',
    //   dataIndex: 'class_number',
    //   key: 'class_number',
    //   width: 80,
    // },

    (() => {
      const teacher_name = {
        title: '班主任',
        dataIndex: 'teacher_name',
        key: 'teacher_name',
        width: 120,
      };
      const care_teacher_name = {
        title: '保育员',
        dataIndex: 'care_teacher_name',
        key: 'care_teacher_name',
        width: 120,
      };
      return Utils.getProps('edu_type') === 'kg' ? care_teacher_name : teacher_name;
    })(),

    {
      title: '班号',
      dataIndex: 'class_number',
      key: 'class_number',
      // width: 120,
    },
    {
      title: '创建日期',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 120,
      render: (text: any) => {
        if (!text) return;
        // eslint-disable-next-line consistent-return
        return dayjs(text).format('YYYY年MM月DD日');
      },
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      fixed: 'right',
      //width: 100,
      align: 'center',
      hidden: !isPermissionOperate(),
      render: (text, record) => {
        return (
          <Space>
            <PermissionButton permission="view">
              <Button
                type="link"
                onClick={() => {
                  setCurrent({ ...record });
                  setShowEditModel(true);
                  setIsEdit(false);
                }}
              >
                查看
              </Button>
            </PermissionButton>
            {!Utils.getProps('isCity') && !Utils.getProps('isCounty') && (
              <>
                <PermissionButton permission="edit">
                  <Button
                    type="link"
                    onClick={() => {
                      setCurrent({ ...record });
                      setShowEditModel(true);
                      setIsEdit(true);
                    }}
                  >
                    编辑
                  </Button>
                </PermissionButton>
                {/* <Popconfirm
                  title="是否确认删除该数据？"
                  onConfirm={delConfirm}
                  onCancel={delCancel}
                  okText="是"
                  cancelText="否"
                >
                  <Button type="link" size="small">
                    删除
                  </Button>
                </Popconfirm> */}
                <PermissionButton permission="delete">
                  <Button
                    type="link"
                    size="small"
                    onClick={() => {
                      Modal.confirm({
                        title: '删除',
                        content: `确定否删除‘${record.class_name}’的相关信息`,
                        onOk: async () => {
                          const r = await deleteClasses(record.id);
                          if (r?.success) {
                            message.success('删除成功');
                            search();
                          } else {
                            message.error(r.user_message);
                            throw new Error();
                          }
                        },
                      });
                    }}
                  >
                    删除
                  </Button>
                </PermissionButton>
              </>
            )}
          </Space>
        );
      },
    },
  ];
  const delConfirm = () => {};
  const delCancel = () => {};
  const newDefaultValue = { is_att_class: false, is_bilingual_class: false };
  const _getSessionOptions = async () => {
    const res = await getSessionOptions();
    setSessionOptions(res);
  };
  const _getGradeOptions = async () => {
    const res = await getGradeOptions();
    setGradeOptions(res);
  };
  React.useEffect(() => {
    search(search);
    _getSessionOptions();
    _getGradeOptions();
  }, []);
  const list = [
    {
      title: '',
      labelCol: { span: 4 },
      wrapperCol: { span: 20 },
      span: 24,
      inputs: [
        {
          label: '班级届别',
          name: 'session_id',
          key: 'session_id',
          required: true,
          inputType: InputType.select,
          renderOption: getSessionOptions,
        },
        {
          label: '班级名称',
          name: 'class_name',
          key: 'class_name',
          span: 24,
          required: true,
          textRange: [0, 20],
        },
        {
          label: '所属班级类型',
          name: 'grade_id',
          key: 'grade_id',
          required: true,
          inputType: InputType.select,
          hidden: Utils.getProps('edu_type') !== 'kg',
          renderOption: getGradeOptions,
        },
        {
          label: '所属年级',
          name: 'grade_id',
          key: 'grade_id',
          required: true,
          inputType: InputType.select,
          hidden: Utils.getProps('edu_type') === 'kg',
          renderOption: getGradeOptions,
        },
        {
          label: '班级',
          name: 'class_index',
          key: 'class_index',
          required: true,
          inputType: InputType.select,
          renderOption: () => {
            const list = [];
            for (let i = 1; i <= 50; i++) {
              list.push({
                label: `${i}班`,
                value: `${i}班`,
              });
            }
            return list;
          },
        },
        // {
        //   label: '当前年级',
        //   name: 'grade_id',
        //   key: 'grade_id',
        //   required: true,
        //   inputType: InputType.select,
        //   renderOption: async () => {
        //     const res = await searchGrades({ school_id: Utils.getProps('schoolInfo')?.school_id }, 1, 1000);
        //     if (res.success) {
        //       return res.data.items.map(item => {
        //         return {
        //           label: item.grade_name,
        //           value: item.id, //JSON.stringify([item.id, item.grade_no]),
        //         };
        //       });
        //     }
        //     return [];
        //   },
        // },
        ...(() => {
          const notKg = [
            // {
            //   label: '班主任姓名',
            //   name: 'teacher_id',
            //   key: 'teacher_id',
            //   inputType: InputType.search,
            //   renderOption: searchTeacherOptions,
            //   formatSubmitValue: (val: any) => {
            //     if (val) {
            //       return val.value;
            //     }
            //     return val;
            //   },
            // },
            {
              label: '班主任姓名',
              name: 'teacher_name',
              key: 'teacher_name',
              required: true,
              inputType: InputType.text,
            },
            {
              label: '班主任身份证件类型',
              name: 'teacher_card_type',
              key: 'teacher_card_type',
              required: true,
              inputType: InputType.select,
              relationFields: ['teacher_id_card'],
              renderOption: ID_TYPE,
            },
            {
              label: '班主任身份证件号',
              name: 'teacher_id_card',
              key: 'teacher_id_card',
              required: true,
              ruleType: (formObjectPanel: FormPanelObject) => {
                const id_type = formObjectPanel.getFieldValue('teacher_card_type');
                if (id_type === 'resident_id_card') {
                  return 'cnPeopleNo';
                }
                return '';
              },
            },
            // {
            //   label: '班主任联系电话',
            //   name: 'teacher_phone',
            //   key: 'teacher_phone',
            //   required: true,
            //   ruleType: RuleType.cnPhone,
            // },
            {
              label: '班主任工号',
              name: 'teacher_job_number',
              key: 'teacher_job_number',
              textRange: [0, 20],
            },
          ];
          const kg = [];
          return Utils.getProps('edu_type') === 'kg' ? kg : notKg;
        })(),

        // {
        //   label: '教育阶段',
        //   name: 'education_stage',
        //   key: 'education_stage',
        //   required: true,
        //   inputType: InputType.select,
        //   renderOption: SCHOOL_TYPE,
        // },
        {
          label: '班号',
          name: 'class_number',
          key: 'class_number',
          textRange: [0, 10],
        },
        ...(() => {
          const notKg = [
            {
              label: '班长',
              name: 'monitor_id',
              key: 'monitor_id',
              inputType: InputType.search,
              hidden: Utils.getProps('edu_type') === 'kg',
              renderOption: searchStudentOptions,
              formatSubmitValue: (val: any) => {
                if (val) {
                  return val.value;
                }
                return val;
              },
            },
            {
              label: '班长学号',
              name: 'monitor_student_number',
              key: 'monitor_student_number',
              hidden: Utils.getProps('edu_type') === 'kg',
              textRange: [0, 20],
            },
            {
              label: '中小学班级类型',
              name: 'class_type',
              key: 'class_type',
              span: 24,
              renderOption: CLASSES_SYSTEM,
              inputType: InputType.select,
              hidden: Utils.getProps('edu_type') === 'kg',
            },
          ];
          const kg = [
            {
              label: '保育员姓名',
              name: 'care_teacher_id',
              key: 'care_teacher_id',
              inputType: InputType.search,
              renderOption: searchTeacherOptions,
              hidden: Utils.getProps('edu_type') !== 'kg',
              formatSubmitValue: (val: any) => {
                if (val) {
                  return val.value;
                }
                return val;
              },
            },
            {
              label: '保育员身份证件类型',
              name: 'care_teacher_card_type',
              key: 'care_teacher_card_type',
              inputType: InputType.select,
              relationFields: ['care_teacher_id_card'],
              renderOption: ID_TYPE,
              hidden: Utils.getProps('edu_type') !== 'kg',
            },
            {
              label: '保育员身份证件号',
              name: 'care_teacher_id_card',
              key: 'care_teacher_id_card',
              hidden: Utils.getProps('edu_type') !== 'kg',
              ruleType: (formObjectPanel: FormPanelObject) => {
                const id_type = formObjectPanel.getFieldValue('care_teacher_card_type');
                if (id_type === 'resident_id_card') {
                  return 'cnPeopleNo';
                }
                return '';
              },
            },
            {
              label: '保育员联系电话',
              name: 'care_teacher_phone',
              key: 'care_teacher_phone',
              ruleType: RuleType.cnPhone,
              hidden: Utils.getProps('edu_type') !== 'kg',
            },
            {
              label: '保育员工号',
              name: 'care_teacher_job_number',
              key: 'care_teacher_job_number',
              textRange: [0, 20],
              hidden: Utils.getProps('edu_type') !== 'kg',
            },
          ];
          return Utils.getProps('edu_type') === 'kg' ? kg : notKg;
        })(),

        // {
        //   label: '学制',
        //   name: 'school_system',
        //   key: 'school_system',
        //   span: 24,
        //   inputType: InputType.select,
        //   renderOption: SCHOOL_SYSTEM,
        // },
        // {
        //   label: '班长',
        //   name: 'monitor',
        //   key: 'monitor',
        //   textRange: [0, 10],
        // },
        // {
        //   label: '中职班级专业',
        //   name: 'major_for_vocational',
        //   key: 'major_for_vocational',
        //   span: 24,
        //   inputType: 'children',
        //   children: <Cascader />,
        //   renderOption: async () => {
        //     const data = await searchMajor(Utils.getProps('schoolInfo')?.school_id);
        //     if (data.success) {
        //       return data.data.items.map(item => {
        //         return {
        //           label: item.major_name,
        //           value: item.major_no,
        //         };
        //       });
        //     }
        //     return [];
        //   },
        // },
        {
          label: '是否少数民族双语教学班',
          name: 'is_bilingual_class',
          key: 'is_bilingual_class',
          span: 24,
          required: false,
          renderOption: YES_NO,
          inputType: InputType.radio,
        },
        {
          label: '是否附设班',
          name: 'is_att_class',
          key: 'is_att_class',
          span: 24,
          required: false,
          renderOption: YES_NO,
          inputType: InputType.select,
          relationFields: ['att_class_type'],
        },
        {
          label: '附设班类型',
          name: 'att_class_type',
          key: 'att_class_type',
          span: 24,
          required: false,
          renderOption: ATTACHED_TYPE,
          inputType: InputType.select,
          hidden: (form: FormPanelObject) => {
            return form.getFieldValue('is_att_class') === false;
          },
        },
      ],
    },
  ];

  const searchList = [
    {
      title: '',
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      inputs: [
        {
          label: '班级届别',
          name: 'session_id',
          key: 'session_id',
          inputType: InputType.select,
          renderOption: getSessionOptions,
        },
        (() => {
          const teacher_id = {
            label: '班主任姓名',
            name: 'teacher_name',
            key: 'teacher_name',
            // inputType: InputType.search,
            // renderOption: searchTeacherOptions,
            // formatSubmitValue: (val: any) => {
            //   if (val) {
            //     return val.value;
            //   }
            //   return val;
            // },
          };
          const care_teacher_name = {
            label: '保育员',
            name: 'care_teacher_name',
            key: 'care_teacher_name',
          };
          return Utils.getProps('edu_type') === 'kg' ? care_teacher_name : teacher_id;
        })(),

        // {
        //   label: '区县',
        //   name: 'borough',
        //   key: 'borough',
        //   inputType: 'select',
        //   inputProps: {
        //     placeholder: '请选择',
        //     allowClear: true,
        //     showSearch: true,
        //     filterOption: utils.filterOption,
        //   },
        //   renderOption: SY_ZONES,
        // },
        // {
        //   label: '学校',
        //   name: 'school_name',
        //   key: 'school_name',
        //   inputType: 'text',
        //   inputProps: {
        //     placeholder: '请输入',
        //     allowClear: true,
        //   },
        // },
        // {
        //   label: '年级',
        //   name: 'grade_id',
        //   key: 'grade_id',
        //   inputType: 'select',
        //   inputProps: {
        //     placeholder: '请选择',
        //     allowClear: true,
        //     showSearch: true,
        //     filterOption: utils.filterOption,
        //   },
        //   renderOption: async () => {
        //     const res = await searchGrades({ school_id: Utils.getProps('schoolInfo')?.school_id }, 1, 1000);
        //     if (res.success) {
        //       return res.data.items.map(item => {
        //         return {
        //           label: item.grade_name,
        //           value: item.id,
        //         };
        //       });
        //     }
        //     return [];
        //   },
        // },
        {
          label: '班级名称',
          name: 'class_name',
          key: 'class_name',
        },
        {
          label: '创建时间',
          name: 'create_at',
          key: 'create_at',
          inputType: InputType.children,
          children: <RangePicker />,
          formatSubmitValue: (val: any) => {
            if (val && val.isValid && val.isValid()) {
              return val.map(item => item.format('YYYY-MM-DD')).join(',');
            }
            return val;
          },
        },
        {
          label: '所属班级类型',
          name: 'class_type',
          key: 'class_type',
          inputType: InputType.select,
          hidden: Utils.getProps('edu_type') !== 'kg',
          renderOption: getGradeOptions,
        },
        // {
        //   label: '所属班级类型',
        //   name: 'class_type',
        //   key: 'class_type',
        //   renderOption: CLASSES_SYSTEM,
        //   inputType: InputType.select,
        //   hidden: Utils.getProps('edu_type') === 'kg',
        // },
        {
          label: '所属年级',
          name: 'grade_id',
          key: 'grade_id',
          renderOption: gradeOptions,
          inputType: InputType.select,
          hidden: Utils.getProps('edu_type') !== 'k12',
        },
        {
          label: '班号',
          name: 'class_number',
          key: 'class_number',
          textRange: [0, 10],
        },
      ],
    },
  ];

  const buildBtns = () => {
    return [];
  };

  const search = async (search?, pageIndex?, pageSize?) => {
    const values = searchForm?.getFieldsValue() || search || {};
    const searchValue: SearchClass = {
      school_id,
      block: values?.borough,
      ...values,
    };
    utils.showLoading();
    const res = await searchClasses(searchValue, pageIndex, pageSize);
    if (res.success) {
      setValue(res.data.items);
      setPageIndex(pageIndex);
      setPageSize(pageSize);
      setTotal(res.data.total);
    }
    utils.hideLoaing(res.success);
  };

  React.useEffect(() => {
    search({}, pageIndex, pageSize);
  }, []);
  const pageChange = (pageIndex, pageSize) => {
    set_stoge_pz(pageSize);
    search(search, pageIndex, pageSize);
  };
  return (
    <PageContainer
      header={
        <Breadcrumb
          items={[
            {
              title: (
                <div>
                  {!isSchool && <LeftOutlined onClick={() => navigator(-1)} />}
                  班级管理
                </div>
              ),
            },
          ]}
        />
      }
    >
      <FormPanel
        btnsAlign={FormPanelBtnAlign.right}
        //buttonsDisplay={FormPanelBtnDisplay.block}
        restBtnText="重置"
        buttons={isSchool ? buildBtns() : []}
        submitBtnText="查询"
        onLoad={(form: FormPanelObject) => {
          setSearchForm(form);
        }}
        onFinish={(formPanelObject: FormPanelObject) => {
          search(formPanelObject.getFieldsValue(), pageIndex, pageSize);
        }}
        template={searchList}
      />
      <Flex gap="small" wrap="wrap" style={{ marginBottom: 20 }}>
        {isSchool && (
          <PermissionButton permission="import">
            <StandUploadExcel
              uploadSrv="/school/v1/storage/school-upload-uri"
              templateUrl={IMPORT_EXCEL_TEMPLATE.class}
              templateName="资源导入模版.xlsx"
              showExcelSrv="/school/v1/storage/file-data-preview"
              scene="class"
              onImport={async (data, file_name, bucket_name) => {
                const res = await importClass({
                  file_name,
                  bucket_name,
                  scene: 'class',
                });
                if (res.success) {
                  message.success('导入成功');
                  search({}, 1, pageSize);
                } else {
                  message.error(res.message || res.details);
                }
                return res.success;
              }}
            >
              导入
            </StandUploadExcel>
          </PermissionButton>
        )}

        {isSchool && (
          <PermissionButton permission="add">
            <Button type="primary" onClick={() => setShowModel(true)}>
              新增
            </Button>
          </PermissionButton>
        )}
      </Flex>
      <Table
        dataSource={value}
        columns={columns}
        scroll={{ x: 'max-content' }}
        pagination={{ ...PAGINATIONCONFIG, total, pageSize, current: pageIndex, onChange: pageChange }}
      />
      <Modal width="80%" title="新增班级" footer={[]} open={showModel} onCancel={() => setShowModel(false)}>
        <FormPanel
          btnsAlign={FormPanelBtnAlign.center}
          buttonsDisplay={FormPanelBtnDisplay.block}
          restBtnText="取消"
          submitBtnText="确定"
          onReset={() => setShowModel(false)}
          onFinish={async (formPanelObject: FormPanelObject) => {
            const values = formPanelObject.getFieldsValue();
            const submitValues: CreateClasses = { ...values };
            submitValues.school_id = Utils.getProps('schoolInfo')?.school_id;

            //const gardeinfo = JSON.parse(values.grade_id);
            //submitValues.grade_id = gardeinfo[0];
            //submitValues.grade_no = gardeinfo[1];
            //submitValues.year_established = values.year_established.format('YYYY');
            //submitValues.major_for_vocational = values?.major_for_vocational?.join(',');
            const res = await createClasses(submitValues);
            if (res.success) {
              message.success('添加成功');
              setShowModel(false);
              search('', pageIndex, pageSize);
              formPanelObject.resetFields();
            } else {
              formPanelObject.reVaildation(res);
            }
            return false;
          }}
          template={list}
          values={newDefaultValue}
        />
      </Modal>
      <Modal
        width="80%"
        title={isEdit ? '编辑班级' : '班级信息查看'}
        footer={[]}
        open={showEditModel}
        onCancel={() => setShowEditModel(false)}
      >
        <FormPanel
          width="80%"
          btnsAlign={FormPanelBtnAlign.center}
          buttonsDisplay={FormPanelBtnDisplay.block}
          restBtnText="取消"
          submitBtnText="确定"
          formStatus={isEdit ? FormPanelStatus.edit : FormPanelStatus.nonEdit}
          onReset={() => setShowEditModel(false)}
          onFinish={async (formPanelObject: FormPanelObject) => {
            const values = formPanelObject.getFieldsValue();
            const submitValues: UpdateClasses = { ...values };
            submitValues.school_id = Utils.getProps('schoolInfo')?.school_id;
            const gardeinfo = JSON.parse(values.grade_id);
            submitValues.grade_id = gardeinfo[0];
            submitValues.grade_no = gardeinfo[1];
            // submitValues.year_established = values.year_established.format('YYYY');
            submitValues.id = current.id;
            const res = await updateClasses(submitValues);
            if (res.success) {
              message.success('编辑成功');
              setShowEditModel(false);
              search('', pageIndex, pageSize);
              //form.resetFields();
            } else {
              formPanelObject.reVaildation(res);
            }
            return false;
          }}
          values={current}
          template={list}
        />
      </Modal>
    </PageContainer>
  );
};

export default Groups;
